package com.teng.smartdrawer;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.teng.gallerylibrary.BaseAdapterHelper;
import com.teng.gallerylibrary.Gallery;
import com.teng.gallerylibrary.QuickPagerAdapter;
import com.teng.smartdrawer.bean.RefreshEvent;
import com.teng.smartdrawer.utils.ImageLoaderTools;
import com.teng.smartdrawer.utils.ImageLoadingConfig;
import com.teng.smartdrawer.utils.PreferenceUtils;
import com.teng.smartdrawer.utils.ScreenUtils;
import com.teng.smartdrawer.view.CircleImageView;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener, ViewPager.OnPageChangeListener, View.OnClickListener {
    private SwipeRefreshLayout mRefreshLayout;
    private int headPosition = 1;
    private SlidingMenu slidMenu;
    private Gallery gallery;
    private QuickPagerAdapter<Bean> mQuickPagerAdapter;
    private List<Bean> data;
    private LinearLayout search_linear;
    private PreferenceUtils preferenceUtils;
    private TextView module_name , module_describe;
    private ImageView main_top_welcome_bg;
    private CircleImageView user_head;
    private TextView user_name;


    public static final int LOGIN_REQUEST = 0x11;

    public static final int LOGOUT_REQUEST = 0x12;

    private int[] topImages = {R.drawable.one_floor , R.drawable.miehuo_car , R.drawable.taiyang_car , R.drawable.four_zhou};


    private ImageLoader imageLoader = ImageLoader.getInstance();
    private DisplayImageOptions imgOptions = ImageLoadingConfig.generateDisplayImageOptionsWithAnimationAndNoCorner(R.mipmap.img_default_home_cover);


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ScreenUtils.setTranslucentStatus(this);
        setContentView(R.layout.activity_main);

        preferenceUtils = PreferenceUtils.getInstance(this);
        setSlidingOption();

        ///////////////  上面的广告位  ///////////////
        mRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.main_refreshlayout);
        mRefreshLayout.setColorSchemeResources(R.color.black, R.color.google_blue, R.color.google_yellow, R.color.google_blue, R.color.google_yellow);
        mRefreshLayout.setDistanceToTriggerSync(500);   // 下拉刷新的距离
        mRefreshLayout.setOnRefreshListener(this);

        main_top_welcome_bg = (ImageView) findViewById(R.id.main_top_welcome_bg);
        ImageLoader.getInstance().displayImage("drawable://"+topImages[headPosition], main_top_welcome_bg);

        /////////////   下面的滑动浏览  ////////////////////
        module_describe = (TextView) findViewById(R.id.module_describe);
        module_name = (TextView) findViewById(R.id.module_name);

        search_linear = (LinearLayout) findViewById(R.id.main_fragment_linear_search);
        search_linear.setOnClickListener(this);

        ImageView main_menu = (ImageView) findViewById(R.id.img_main_fragment_sliding);
        main_menu.setOnClickListener(this);

        data = new ArrayList<Bean>();
//        data.add(new Bean(R.drawable.a, R.string.describe_string_a , R.string.demo_string_a));
        data.add(new Bean(R.drawable.b, R.string.describe_string_b ,R.string.demo_string_b));
        data.add(new Bean(R.drawable.c, R.string.describe_string_c ,R.string.demo_string_c));
        data.add(new Bean(R.drawable.d, R.string.describe_string_d ,R.string.demo_string_d));
        data.add(new Bean(R.drawable.e, R.string.describe_string_e, R.string.demo_string_e));
//        data.add(new Bean(R.drawable.f, R.string.describe_string_f ,R.string.demo_string_f));
//        data.add(new Bean(R.drawable.g, R.string.describe_string_g ,R.string.demo_string_g));
//        data.add(new Bean(R.drawable.h, R.string.describe_string_h ,R.string.demo_string_h));
//        data.add(new Bean(R.drawable.i, R.string.describe_string_i, R.string.demo_string_i));
//        data.add(new Bean(R.drawable.j, R.string.describe_string_j, R.string.demo_string_j));
//        data.add(new Bean(R.drawable.k, R.string.describe_string_k, R.string.demo_string_k));

        mQuickPagerAdapter = new QuickPagerAdapter<Bean>(this, R.layout.gallery_item_layout, data) {
            @Override
            protected void convertView(BaseAdapterHelper helper, final Bean item) {

                View view = helper.getView();

                ImageView imageView = (ImageView) view.findViewById(R.id.imageview);

                ImageLoader.getInstance().displayImage("drawable://" + item.getImgResId(),  imageView , imgOptions);

                helper.setImageOnClickListener(R.id.imageview, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });
            }
        };

        gallery = (Gallery) findViewById(R.id.gallery);
        gallery.setAdapter(mQuickPagerAdapter);

        /////////////////   ViewPager的一些操作  ///////////////////////
        gallery.getViewPager().addOnPageChangeListener(this);
        gallery.getViewPager().setCurrentItem(1);
        gallery.getViewPager().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO 解决ViewPager和SwipeRefreshLayout的滑动冲突
                switch (event.getAction()) {
                    case MotionEvent.ACTION_MOVE:
                        mRefreshLayout.setEnabled(false);
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        mRefreshLayout.setEnabled(true);
                        break;
                }
                return false;
            }
        });

        // 注册EventBus监听器
        EventBus.getDefault().register(this);

    }


    @Override
    public void onRefresh() {
        // TODO 下拉刷新的事件处理
        headPosition++;
        if (headPosition == topImages.length){
            headPosition = 0;
        }

        //ImageLoader.getInstance().displayImage("drawable://"+topImages[headPosition] , main_top_welcome_bg);

        ImageLoader.getInstance().loadImage("drawable://"+topImages[headPosition], imgOptions , new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String s, View view) {

            }

            @Override
            public void onLoadingFailed(String s, View view, FailReason failReason) {

            }

            @Override
            public void onLoadingComplete(String s, View view, Bitmap bitmap) {

                main_top_welcome_bg.setImageBitmap(bitmap);
                mRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onLoadingCancelled(String s, View view) {

            }
        } );
    }


    private boolean notifyUser(){
        // TODO 提示用户当前的操作权限
        boolean ret = false;
        if (!preferenceUtils.getBoolean(PreferenceUtils.USER_IS_LOGIN , false) ){
            Toast.makeText(this , "请先登录" , Toast.LENGTH_SHORT).show();
        }else {
            // 已经登录
            if (!preferenceUtils.getString(PreferenceUtils.USER_AUTHORITY , "-1") .equals ("3")){
                Toast.makeText(this , "没有权限进行此操作" , Toast.LENGTH_SHORT).show();
            }else {
                ret = true;
            }
        }

        return ret;
    }



    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.img_main_fragment_sliding :
                // TODO 侧滑菜单
                if (!slidMenu.isMenuShowing()) {
                    slidMenu.showMenu();//显示左菜单（主菜单）
                } else {
                    slidMenu.toggle();
                }
                break;
            case R.id.main_fragment_linear_search :
                // TODO 搜索
                boolean b = notifyUser();
                if (!b)
                    return;
                Intent toSearch = new Intent(this , SearchActivity.class);
                startActivity(toSearch);
                break;
            case R.id.component_find:
                // TODO 零件查找
                boolean c = notifyUser();
                if (!c)
                    return;
                Intent toComponentSearch = new Intent(this , SearchComponentActivity.class);
                startActivity(toComponentSearch);
                break;
            case R.id.module_find:
                // TODO 模块查找
                boolean e = notifyUser();
                if (!e)
                    return;
                Intent toModuleSearch = new Intent(this , SearchModuleActivity.class);
                startActivity(toModuleSearch);
                break;
            case R.id.about_app:
                // TODO 关于
                Intent aboutIntent = new Intent(this , AboutActivity.class);
                startActivity(aboutIntent);
                break;
            case R.id.buy_component:
                //TODO 购买
                boolean d = notifyUser();
                if (!d)
                    return;
                Intent buyIntent = new Intent(this , BuyActivity.class);
                startActivity(buyIntent);
                break;
            case R.id.login_linear:
                //TODO 登录
                if (preferenceUtils.getBoolean(PreferenceUtils.USER_IS_LOGIN , false)){
                    Intent logOutIntent = new Intent(this, LogOutActivity.class);
                    startActivityForResult(logOutIntent , LOGOUT_REQUEST);
                }else {
                    Intent goMainIntent = new Intent(this, LoginActivity.class);
                    startActivityForResult(goMainIntent, LOGIN_REQUEST);
                }
                break;
            default:
                break;
        }
    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == LOGIN_REQUEST && resultCode == RESULT_OK){
//            user_name.setText(preferenceUtils.getString(PreferenceUtils.USER_NAME, "小哥爱学习"));
//            String pic_url = preferenceUtils.getString(PreferenceUtils.USER_HEAD_PIC, "http://image.16888.com/picLib/57490/118165/2010122716392442_thumb800_600.jpg");
//            ImageLoader.getInstance().displayImage(pic_url , user_head , imgOptions);
//        }
//        if (requestCode == LOGOUT_REQUEST && resultCode == RESULT_OK){
//            user_name.setText("登录");
//            user_head.setImageResource(R.mipmap.user_default);
//        }
//    }

    private void setSlidingOption(){

        slidMenu = new SlidingMenu(this);
        slidMenu.setMode(SlidingMenu.SLIDING_WINDOW);//左菜单
        slidMenu.setMenu(R.layout.slideing_layout);
        //设置菜单侧滑出来的触摸方式，不能手动出
        slidMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
        // 设置渐入渐出效果的值
        slidMenu.setFadeDegree(0.35f);
        // 设置菜单侧滑出来的宽度(屏幕的3/4)
        slidMenu.setBehindWidth((int)
                (getResources().getDisplayMetrics().widthPixels * 0.75f));//单位：px
        //slidMenu.setBehindOffset(300);//设置菜单侧滑出来后，内容页面显示的宽度
        //设置菜单的归属模式
        slidMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT , true);

        View menu = slidMenu.getMenu();
        /////////////////    侧滑菜单    //////////////////
        LinearLayout buy_component = (LinearLayout) menu.findViewById(R.id.buy_component);
        buy_component.setOnClickListener(this);

        LinearLayout component_find = (LinearLayout) menu.findViewById(R.id.component_find);
        component_find.setOnClickListener(this);

        LinearLayout module_find = (LinearLayout) menu.findViewById(R.id.module_find);
        module_find.setOnClickListener(this);

        LinearLayout login_linear = (LinearLayout) menu.findViewById(R.id.login_linear);
        login_linear.setOnClickListener(this);

        LinearLayout about_app = (LinearLayout) menu.findViewById(R.id.about_app);
        about_app.setOnClickListener(this);

        user_name = (TextView) menu.findViewById(R.id.user_name);
        user_head = (CircleImageView) menu.findViewById(R.id.user_head);

        // 是否登录
        if (preferenceUtils.getBoolean(PreferenceUtils.USER_IS_LOGIN , false)){
            user_name.setText(preferenceUtils.getString(PreferenceUtils.USER_NAME, "小哥爱学习"));
            String pic_url = preferenceUtils.getString(PreferenceUtils.USER_HEAD_PIC, "http://image.16888.com/picLib/57490/118165/2010122716392442_thumb800_600.jpg");
            ImageLoader.getInstance().displayImage(pic_url , user_head);
        }else {
            user_name.setText("登录");
            user_head.setImageResource(R.mipmap.user_default);
        }

    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        Bean bean = data.get(position);
        module_describe.setText(bean.getStrResId());
        module_name.setText(bean.getNameResId());
    }

    @Override
    public void onPageScrollStateChanged(int state) {



    }


    public void onEventMainThread(RefreshEvent event) {
        // TODO 接收登录成功消息
        user_name.setText(preferenceUtils.getString(PreferenceUtils.USER_NAME, "小哥爱学习"));
        String pic_url = preferenceUtils.getString(PreferenceUtils.USER_HEAD_PIC, "http://image.16888.com/picLib/57490/118165/2010122716392442_thumb800_600.jpg");
        ImageLoader.getInstance().displayImage(pic_url , user_head , imgOptions);

    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {

            count = 0;

            return false;
        }
    });


    private int count = 0;

    @Override
    public void onBackPressed() {
        //super.onBackPressed();

        count++;

        if (count == 1){
            Toast.makeText(MainActivity.this , "再按一次返回退出" ,Toast.LENGTH_SHORT).show();
            handler.sendEmptyMessageDelayed(0x11 , 2000);       // 两秒内没有按返回，重新计时
        }else if (count == 2){
            finish();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
